<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\Validate;
use think\facade\Request;
use think\facade\Session;
use app\model\QuestionModel;
use app\Common;

//产品控制器
class Question{

    //常用数据表内容 及常用字典
    var $goods=[];
    var $users =[];
    var $status=array('1'=>'正常','2'=>'停用');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";
    var $type =array(1=>'单选题',2=>'多选题',3=>'判断题');


    var $answer_arr=array(
        "1"=>"A",
        "2"=>"B",
        "3"=>"C",
        "4"=>"D",
        "7"=>"A,B",
        "8"=>"A,C",
        "9"=>"A,D",
        "10"=>"B,C",
        "11"=>"B,D",
        "12"=>"C,D",
        "13"=>"A,B,C",
        "14"=>"A,B,D",
        "15"=>"A,C,D",
        "16"=>"B,C,D",
        "17"=>"A,B,C,D"
    );   
    var $answer_arr2=array(
        "A"=> "1",
        "B"=> "2",
        "C"=> "3",
        "D"=> "4",
        "A,B"=> "7",
        "A,C"=> "8",
        "A,D"=> "9",
        "B,C"=>"10",
        "B,D"=>"11",
        "C,D"=>"12",
        "A,B,C"=>"13",
        "A,B,D"=>"14",
        "A,C,D"=>"15",
        "B,C,D"=>"16",
        "A,B,C,D"=>"17"
    );  


    public function __construct(){
        //准备一个类型数组

        // $gm=new GoodsModel();
        // $this->goods = $gm->getAll();

        $list = Db::table("user")->select()->toArray();
        foreach($list as $k=>$v){
            $this->users[$v['id']]=$v;
        }   

    }

    public function getImgs($imgs=''){
        if(!$imgs) return '';
        $arr = explode(",",$imgs);
        return implode(",",$arr);
    }

    //Goods controller index method
    public function index($page=1){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $question = new QuestionModel();//模型跟controller同名会有问题

        $all = Request::param();
        $list = Db::table('question');
        $type='';
        $subject='';
        $model='';

        if(!empty($all['model'])){
            $list=$list->where('model',$all['model']);
            $model=$all['model'];
        }

        if(!empty($all['type'])){
            $list=$list->where('type',$all['type']);
            $type=$all['type'];
        }

        if(!empty($all['subject'])){
            $subject=$all['subject'];
            $list=$list->where('subject',$all['subject']);
        }

        $title ='';
        if(!empty($all['title'])){
            $title = $all['title'];
            $list = $list->where('title','like','%'.$title.'%');
        }

        $list = $list->order('id')->paginate(15)->toArray();

        foreach($list['data'] as &$v){
            // $v['creater_name'] =$this->users[$v['creater']]['name'];
            $v['status_name']=$this->status[$v['status']];
            $v['type_name']=$this->type[$v['type']];
            $v['image'] = !empty($v['image'])? ($v['image']):'';

        }
    
        $sys = Db::table('sys')->find(1);

        //halt($this->goodsType);
        View::assign(['list'=>$list,'title'=>$title,'type'=>$type,'subject'=>$subject,'model'=>$model]);
        return View::fetch();
    }

    //考试
    public function test(){
        $list =[];

        $all=Request::param();
        if(empty($all['kemu']) || !($all['kemu']==1 || $all['kemu']==4)) return json(['code'=>0,'msg'=>'科目选择错误!']);

        $kemu = $all['kemu'];
        $model = strtoupper($all['model']);


        if($model=='C1,C2'){
            if($kemu==1){
                $list1 = Db::table('question')->where('model','in',$model)->where('type',1)->where('subject',$kemu)->orderRaw('rand()')->limit(60)->select()->toArray();
                $list2 = Db::table('question')->where('model','in',$model)->where('type',3)->where('subject',$kemu)->orderRaw('rand()')->limit(40)->select()->toArray();
                $list3 =[];
            }


            if($kemu==4){
                $list1 = Db::table('question')->where('model','in',$model)->where('type',1)->where('subject',$kemu)->orderRaw('rand()')->limit(20)->select()->toArray();
                $list2 = Db::table('question')->where('model','in',$model)->where('type',3)->where('subject',$kemu)->orderRaw('rand()')->limit(20)->select()->toArray();
                $list3 = Db::table('question')->where('model','in',$model)->where('type',2)->where('subject',$kemu)->orderRaw('rand()')->limit(10)->select()->toArray();
            }
            $list = array_merge($list1,$list2,$list3);
        }else if($model=='D,E,F'){
            if($kemu==1){
                $list1 = Db::table('question')->where('model',$model)->where('subject',$kemu)->orderRaw('rand()')->limit(100)->select()->toArray();
            }else{
                $list1 = Db::table('question')->where('model',$model)->where('subject',$kemu)->orderRaw('rand()')->limit(50)->select()->toArray();

            }
            $list = $list1;
        }else if($model='SL'){
                $list1 = Db::table('question')->where('model',$model)->orderRaw('rand()')->limit(50)->select()->toArray();            
        }
        
        //halt($list);
        foreach($list as &$item){
            $item['options']= json_decode($item['options'],true);
            if($item['type']==3){
                unset($item['options'][2]);
                unset($item['options'][3]);
            }
        }

        return json(['code'=>1,'data'=>$list]);
    }

    //考试历史查询及写入
    public function test_log(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'登录后才能操作！']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $me = $arr['customer'];  
        //$me=Db::table('customer')->find(1073);

        if(!empty($all['log_post'])){
            $pass='';
            if($all['subject']==1){
                $pass = ($all['score']>=90)?'及格':'不及格';
            }else if($all['subject']==4){
                $pass = ($all['score']>=80)?'及格':'不及格';
            }

            $arr=array(
                'customer_id'=>$me['id'],
                'model'=>$all['model'],
                'subject'=>$all['subject'],
                'score'=>$all['score'],
                'pass'=>$pass,
                'create_time'=>date('Y-m-d H:i:s')
            );

            $res =Db::table('test_log')->insert($arr);
            if($res) return json(['code'=>1,'msg'=>'ok']);

            return json(['code'=>0,'msg'=>'写入失败！']);

        }

        $list = Db::table('test_log')->where('customer_id',$me['id'])->order('create_time','desc')->select()->toArray();
        foreach($list as &$item){
            if($item['subject']==1){
                $item['subject']="科目一";
            }else if($item['subject']==4){
                $item['subject']='科目四';
            }else if($item['subject']==3){
                $item['subject']='三力测试';
            }
        }
        $max_score = Db::query('select max(score) as max_score from test_log where customer_id=?',[$me['id']]);
        if(!$max_score[0]['max_score']) $max_score[0]['max_score']=0;

        return json(['code'=>1,'msg'=>'ok','data'=>$list,'max_score'=>$max_score[0]['max_score']]);

    }

    //产品编辑方法
    public function edit(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');

        $all = Request::param();
        if(empty($all['id'])) return 'Invalid item id!'.$this->back ;

        $question = new QuestionModel();

        //传入内容,保存数据并跳转
        if($all['id']>0 && !empty($all['title'])){
            //检测重复数据
            // if($all['price']<0) return '价格错误，稍后返回！'.$this->back;

            $ex = Db::query("select * from question where id<>? and title=?",array($all['id'],$all['title']));
            if(count($ex)) {
                return '题目重复!'.$this->back;
            }

            if($all['type']!=2 && strlen($all['answer'])>1){
                return '单选和判断题,答案只能选一个!'.$this->back;
            }
            $all['creater']  = $uid;
            //halt($all);

            $res =$this->save_q($all);
            return header('location:/index.php/question');
        }

        //不传内容只有id,查出本条数据 并进入编辑
        $row = $question->find($all['id'])->toArray();
        $row['options']=json_decode($row['options'],true);


        View::assign(['data'=>$row]);
        return View::fetch();
    }


    public function question_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header('location:/index.php/login');
        $all = Request::param();

        if(!empty($all['title']) && !empty($all['answer'])){

            if(!empty($all['id'])) return '不是一个新的!'.$this->back;

            if($all['type']!=2 && strlen($all['answer'])>1){
                return '单选和判断题,答案只能选一个!'.$this->back;
            }

            $row = Db::table('question')->where('title',$all['title'])->find();
            if(!empty($row)) return '题目存在!  ['. $all['title']."]".$this->back;
            
            $all['creater']  = $uid; 

            //halt($all);

            $res =$this->save_q($all);
            if(!$res['code']) return $res['msg'].$this->back ;
            return header('location:/question/index');
        }
        return View::fetch();
    }


    public function save_q($all){
        if(!$all) return ['code'=>0,'msg'=>'error'];

        $op=[];
        if(!empty($all['option1'])) {
            $op[] = array('key'=>'A','val'=>$all['option1']);
        }else{
            return ['code'=>0,'msg'=>'A,B选择不能空！'];
        }
        if(!empty($all['option2'])) {
            $op[] = array('key'=>'B','val'=>$all['option2']);
        }else{
            return ['code'=>0,'msg'=>'A,B选择不能空！'];
        }
        if(!empty($all['option3'])) {
            $op[] = array('key'=>'C','val'=>$all['option3']);
        }
        if(!empty($all['option4'])) {
            $op[] = array('key'=>'D','val'=>$all['option4']);
        }
        $all['options']=$op;

        $arr = array(
            'model'=>$all['model'],
            'type'=>$all['type'],
            'title'=>$all['title'],
            'subject'=>$all['subject'],
            'options'=>json_encode($op,JSON_UNESCAPED_UNICODE),
            'answer'=>strtoupper($all['answer']),
            'desc'=>$all['desc'],
            'status'=>$all['status'],
            'create_time'=>date('Y-m-d H:i:s'),
            'creater'=>$all['creater']
        );
        if(!empty($all['id'])){$arr['id']=$all['id'];}

        if($_FILES['file']['size']>0){
            $files =Common::upload();
            
            if($files['code']){
                $arr['image']=$files['msg'];
            }else{
                return ($files['msg']);
            }
        }            

        $res=Db::table('question')->save($arr);  
        return ['code'=>1,'msg'=>$res];      
    }


    public function js_init(){
        $all = Request::param();

        $json_file =$all['jf'];

        // $page = $all['page'];
        // $url="https://api.jisuapi.com/driverexam/query";
        // $query=http_build_query([
        //     'appkey'=>'3a41113f971eabe4',
        //     'type'=>'D',
        //     'subject'=>'1',
        //     'pagesize'=>100,
        //     'pagenum'=>$page,
        //     'sort'=>'normal'
        // ]);

        //$data = file_get_contents('static/js'.$json_file.'.json');
        $data = file_get_contents('static/jsd'.$json_file.'.json');

        $data = json_decode($data,true);

        //$url ="https://api.jisuapi.com/driverexam/query?appkey=3a41113f971eabe4&type=D&subject=1&pagesize=100&pagenum=".$page."&sort=normal";
        //$data = str_replace(PHP_EOL,'',$data);

        //$data = $this->curl_post($url,$query);

        foreach($data['result']['list'] as &$q){

            $q['subject']=$all['subject'];
            Db::table('jisu_question')->insert($q);
        }
        echo 'ok';

    }

    public function jisu_save(){
        $data = Db::table('question')->where('model','D,E,F')->select()->toArray();


        foreach($data as &$row){
            $row['answer'] =$this->answer_arr[$row['answer']];
            Db::table('question')->update($row);
        }

        return 'ok';


        foreach($data as $row){

            $type=0;
            if($row['answer']=='对' || $row['answer']=='错'){
                $type=3;
            }else if(strlen($row['answer'])==1){
                $type=1;
            }else{
                $type=2;
            }

            $options = array(
                ['key'=>'A','val'=>$row['option1']],
                ['key'=>'B','val'=>$row['option2']],
                ['key'=>'C','val'=>$row['option3']],
                ['key'=>'D','val'=>$row['option4']],
            );
            $answer ='';
            if($row['answer']=='对'){
                $answer=1;  
            } else if($row['answer']=='错') {
                $answer=2;
            }else{
                $answer= $this->answer_arr2[$row['answer']];
            }

            $arr = array(
                'subject'=>$row['subject'],
                'model'=>'D,E,F',
                'type'=>$type,
                'title'=>$row['question'],
                'options'=>json_encode($options,JSON_UNESCAPED_UNICODE),
                'answer'=>$answer,
                'desc'=>$row['explain'],
                'image'=>$row['pic']
            );

            Db::table('question')->insert($arr);


        }

        halt('ok');


    }


    public function curl_post($url,$query){
        $ch = curl_init();

        //CURLOPT_URL   需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。
        curl_setopt($ch,CURLOPT_URL,$url.$query);

        //CURLOPT_HTTPGET   true 时会设置 HTTP 的 method 为 GET，由于默认是 GET，所以只有 method 被修改时才需要这个选项。
        curl_setopt($ch,CURLOPT_HTTPGET,true);

        //CURLOPT_HEADER    启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch,CURLOPT_HEADER,false);

        //CURLOPT_RETURNTRANSFER    true 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        // 抓取URL并把它传递给浏览器

        $apiData = curl_exec($ch); 

    
        $data = json_decode($apiData,true);
        //关闭cURL资源，并且释放系统资源
        curl_close($ch);

        return $data;

    }

    public function tk_init(){
        $url = 'http://v.juhe.cn/jztk/query?';
        $key = '304dde4f5025a4d6eec392b0c15fcb1b';
        $subject = 4;
        $model = 'c2';
        $testType = 'order'; //  rand随机100道/order：全部

        //顺序： c1/1,c1/4,c2/1,c2/4

        //http_build_query — 生成 URL-encode 之后的请求字符串
        $query = http_build_query([
        'subject'=>$subject,
        'model'=>$model,
        'testType' =>$testType,
        'key'=>'304dde4f5025a4d6eec392b0c15fcb1b',
        ]);


        //curl_init — 初始化 cURL 会话
        $ch = curl_init();

        //curl_setopt — 设置 cURL 传输选项
        //CURLOPT_URL   需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。
        curl_setopt($ch,CURLOPT_URL,$url.$query);

        //CURLOPT_HTTPGET   true 时会设置 HTTP 的 method 为 GET，由于默认是 GET，所以只有 method 被修改时才需要这个选项。
        curl_setopt($ch,CURLOPT_HTTPGET,true);

        //CURLOPT_HEADER    启用时会将头文件的信息作为数据流输出。
        curl_setopt($ch,CURLOPT_HEADER,false);

        //CURLOPT_RETURNTRANSFER    true 将curl_exec()获取的信息以字符串返回，而不是直接输出。
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        // 抓取URL并把它传递给浏览器

        $apiData = curl_exec($ch);
        $data = json_decode($apiData,true);
        //关闭cURL资源，并且释放系统资源
        curl_close($ch);

        foreach ($data['result'] as $key => $value) {
            $item =$value;

            $options = array(
                ['key'=>'A','val'=>$item['item1']],
                ['key'=>'B','val'=>$item['item2']],
                ['key'=>'C','val'=>$item['item3']],
                ['key'=>'D','val'=>$item['item4']],
            );
            $type=0;
            if($item['item3']<'1' && $item['item4']<'1'){
                $type=3;
            }else if($item['answer']<=4){
                $type=1;
            }else{
                $type=2;
            }

            $arr = array(
                //'id'=>$item['id'],
                'subject'=>$subject,
                'model'=>$model,
                'type'=>$type,
                'title'=>$item['question'],
                'options'=>json_encode($options,JSON_UNESCAPED_UNICODE),
                'answer'=>$this->answer_arr[$item['answer']],
                'desc'=>$item['explains'],
                'image'=>$item['url']

            );

            Db::table('question')->insert($arr);

        }

        echo 'ok';

    // $dataXX=array('reason'=>'ok',
    //     'result'=>array(
    //     "id"=>"1",
    //     "question"=>"这个标志是何含义？",
    //     "answer"=>"4",
    //     "item1"=>"小型车车道",
    //     "item2"=>"小型车专用车道",
    //     "item3"=>"多乘员车辆专用车道",
    //     "item4"=>"机动车车道",
    //     "explains"=>"此为机动车车道，比多乘员车辆专用车道少俩人。",
    //     "url"=>"https://images.juheapi.com/jztk/c1c2subject1/1.jpg"
    //     ),
    //     'errorCode'=>'0');


    // {
    //     "id":"414",
    //     "question":"如图所示，在这种情况下要充分减速靠右行驶。",
    //     "answer":"1",
    //     "item1":"对",
    //     "item2":"错",
    //     "item3":"",
    //     "item4":"",
    //     "explains":"遇到急转鸯路应当提前减速慢行，等到进入弯路后减速很容易发生侧滑或侧翻。",
    //     "url":"https:\/\/images.juheapi.com\/jztk\/subject4\/414.jpg"
    // },
      
    }


}
